﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CRL
{
    class CharObfuscate
    {
        static Dictionary<char, char> masks;
        static ConcurrentDictionaryEx<string, string> convertCache = new ConcurrentDictionaryEx<string, string>();
        static CharObfuscate()
        {
            var chars2 = "abcdefghijklmnopqrstuvwxyz";
            RandomArr(chars2.ToCharArray());
            //chars = "liezcmqjahgoswupbrtyfvnkdx";
            var chars = SettingConfig.ObfuscateChars;
            masks = new Dictionary<char, char>();
            for (var i = 0; i < chars.Length; i++)
            {
                var c = chars[i];
                var m = chars[chars.Length-1 - i];
                masks.Add(c, m);
            }
        }
        static void RandomArr(char[] arr)
        {
            Random r = new Random();//创建随机类对象，定义引用变量为r
            for (int i = 0; i < arr.Length; i++)
            {
                int index = r.Next(arr.Length);//随机获得0（包括0）到arr.Length（不包括arr.Length）的索引
                //Console.WriteLine("index={0}", index);//查看index的值
                var temp = arr[i];  //当前元素和随机元素交换位置
                arr[i] = arr[index];
                arr[index] = temp;
            }
            var text = string.Join("", arr);
        }
        public static string Convert(string text)
        {
            if(string.IsNullOrEmpty(text))
            {
                return text;
            }
            text = text.ToLower();
            var a = convertCache.TryGetValue(text, out var c);
            if (a)
            {
                return c;
            }
            c = "";
            if (text.Length < 6)
            {
                var len = 6 - text.Length;
                text += SettingConfig.ObfuscateChars.Substring(6, len);
            }
            foreach(var l in text)
            {
                var b = masks.TryGetValue(l, out var l2);
                if(!b)
                {
                    l2 = l;
                }
                c += l2.ToString();
            }
            c = c.ToUpper();
            convertCache.TryAdd(text, c);
            return c;
        }
    }
}
